# -*- coding: utf-8 -*-s
import os
from settings import _browser, db, STATICFILES_DIRS


class B2b():
    """
    Class of distributor distributors
    """
    browser = _browser
    rules = {}
    baseAttrib = {}
    currency = 8
    brand_name = [
        "Элна",
        "Модуль",
        "Калитва",
        "Журавинка",
        "другой",
        "Барьер",
        "АКОГ",
        "Аквафор",
        "Ай Ти Лайн",
        "Zelmer",
        "Термия",
        "Термія",
        "Zanussi",
        "Zalman",
        "HTC",
        "1С",
        "1C",
        "@Lux",
        "A-Data",
        "A4-Tech",
        "ABBYY",
        "ACC ",
        "Acer",
        "Acme",
        "Acronis",
        "Adobe",
        "AEG",
        "AeroCool",
        "Ahead",
        "Alan",
        "Alcatel ",
        "Amazon",
        "Amber",
        "AMD",
        "Apple",
        "Aquaheat",
        "Ardo",
        "Ariston",
        "ASRock",
        "Assistant",
        "Asus",
        "Atcom",
        "Atlant",
        "Audioquest",
        "Aurora ",
        "Bandridge",
        "Barnes&Noble",
        "Barva",
        "BBK",
        "Beko",
        "Belkin",
        "BenQ",
        "Biostar",
        "BitDefender",
        "Bosch",
        "Brain",
        "Braun",
        "Bravo",
        "Cal-Comp",
        "Candy",
        "Canon",
        "Canyon",
        "Case Logic ",
        "Cliptec",
        "Codegen",
        "ColorWay",
        "Continent",
        "CoolerMaster",
        "Corel",
        "Corsair",
        "Cosmo",
        "D-Link",
        "Daewoo",
        "Deepcool",
        "Defender",
        "Delfa",
        "Dell",
        "Dicota Base",
        "Digitus",
        "Divoom ",
        "Dr. Web",
        "DWT",
        "Edifier",
        "Electrolux",
        "Elite",
        "Elixir",
        "Enot",
        "Epson",
        "Ergo",
        "Eset",
        "Everest",
        "EvroMedia",
        "F&D",
        "F&K Technology",
        "Flama",
        "Franke",
        "Fujifilm",
        "Fujitsu ",
        "Fujitsu ",
        "G-Cube",
        "Garmin",
        "Gazer",
        "Gemix",
        "Genius",
        "Gigabyte ",
        "Gigabyte ",
        "Globex",
        "GMB",
        "GoClever",
        "Goodram",
        "Gorenje",
        "Grand",
        "Grand-X",
        "Gresso",
        "HackeR",
        "Hansa",
        "HIS",
        "Hitachi",
        "Hotpoint-Ariston",
        "HP ",
        "HP ",
        "Huawei",
        "Hynix",
        "Hyundai",
        "IconBIT",
        "Impression",
        "Indesit",
        "InnoVision",
        "Intel",
        "Interline",
        "iRiver",
        "ITcomp",
        "Kaspersky",
        "Kingston",
        "Kladovka",
        "Konoos ",
        "Korting",
        "Kuppersbusch",
        "LaCie",
        "Lenovo",
        "Lenspen",
        "LG ",
        "LG ",
        "Liberton",
        "Liberty",
        "Liebherr",
        "Logan",
        "Logicfox",
        "Logitech",
        "Luminarc",
        "Magio",
        "Magneo ",
        "Manhattan",
        "Maxxtro",
        "MicroLab",
        "Microsoft",
        "Miele",
        "Mirta",
        "Mitsumi",
        "Mora",
        "Motorola",
        "Moulinex",
        "MSI",
        "Mystery",
        "Navon",
        "NCP",
        "Nikon",
        "Nokia",
        "Nord",
        "Novatel",
        "OKey ",
        "OKtet",
        "Olympus",
        "Orion",
        "Packard Bell",
        "Palit",
        "Panasonic",
        "Panda",
        "Pantech",
        "Patriot",
        "Patron",
        "Payless",
        "PCLand-4U",
        "Pentax",
        "Philips",
        "Pioneer",
        "Pleomax",
        "PocketBook",
        "Port Designs",
        "Porto",
        "PowerColor",
        "PowerCom",
        "PQI",
        "Prestigio",
        "Pretec",
        "PrimePC",
        "Promate",
        "Promt",
        "Qumo",
        "Rapoo",
        "Razer ",
        "Rowenta",
        "Samsung ",
        "Samsung ",
        "SanDisk",
        "Sanyoo ",
        "Sapphire",
        "Saturn",
        "Scarlett",
        "SGP",
        "Sharp",
        "Siemens",
        "Sierra",
        "Sigma ",
        "Silicon Power",
        "Sinbo",
        "Sinotex",
        "Smeg",
        "Snaige",
        "SolarWind",
        "Sony ",
        "Sony ",
        "Speedlink",
        "Spire",
        "Steelseries ",
        "Sumdex",
        "Super Power",
        "SuperComp",
        "SuperTalent",
        "Supra",
        "Sven ",
        "Sweex",
        "Swizer",
        "Symantec",
        "Systemnik",
        "Systemnic",
        "TakeMS",
        "Targa",
        "Targus",
        "TDK",
        "Team",
        "Tefal",
        "Teka",
        "Tenex",
        "Thermex",
        "Titan",
        "Toshiba ",
        "Toshiba ",
        "TP-Link ",
        "Transcend",
        "Tt eSPORTS",
        "uBook",
        "Utstarcom",
        "Vantastic",
        "Velbon ",
        "Verbatim",
        "Verizon",
        "Vestfrost",
        "Viewcon",
        "ViewSonic",
        "VT Computers",
        "Wexler",
        "Whirlpool",
        "Wrapsol",
        "WWM",
        "X-Digital",
        "Seagate"]


    def __init__(self):
        pass

    def login(self):
        """
        Login into distributors distributor site

        """
        pass

    def isLogin(self, page):
        """
        Verify og logging

        :param page: string, page of verify
        """
        pass

    def searchBySitePage(self, query, categoryName):
        """
        Search in distributors distributor site

        :param query: string, query of search
        :param categoryName: string, where in category search
        """
        pass

    def parsing(self):
        """


        """
        pass

    def handlerHtmlCatalog(self, **kwargs):
        """
        Parsing main catalog page distributors distributor site.

        :param kwargs: parameters for parsing
        """
        pass

    def handlerHtmlCategory(self, **kwargs):
        """
        Parsing category page distributors distributor site.

        :param kwargs: parameters for parsing
        """
        pass

    def handlerHtmlProduct(self, **kwargs):
        """
        Parsing product page distributors distributor site

        :param kwargs: parameters for parsing
        """
        pass

    def getAttributeSets(self, attrSetName=None):
        """
        Get attribute in attribute sets

        :param attrSetName: string, if only attribute set
        :return: dict
        """
        if attrSetName:
            attrsSetName_ = db.sqlQuery(
                'SELECT * FROM firsteav_attribute_set where entity_type_id=4 '
                'and attribute_set_name=\'%s\';' % attrSetName)
        else:
            attrsSetName_ = db.sqlQuery('SELECT * FROM firsteav_attribute_set where entity_type_id=4;')
        attrsSetName = {}
        for attrSetName in attrsSetName_:
            attrsSetName[attrSetName[0]] = attrSetName[2].decode('utf-8', 'ignore')
        attrsSet_ = db.sqlQuery('SELECT * FROM firsteav_entity_attribute where entity_type_id=4;')
        attrsSet = {}
        for attrSet in attrsSet_:
            if attrSet[2] in attrsSetName:
                if not attrsSetName[attrSet[2]] in attrsSet:
                    attrsSet[attrsSetName[attrSet[2]]] = {}
                value = self.getAttributeValue(attrSet[4])
                if value:
                    attrsSet[attrsSetName[attrSet[2]]].update(value)
        return attrsSet

    def getAttributeValue(self, attrId):
        """
        Get attribute value by id

        :param attrId: integer
        :return: dict
        """
        attr_ = db.sqlQuery('SELECT * FROM firsteav_attribute where attribute_id=%s' % attrId)
        value = []
        if not attr_:
            return False
        if attr_[0][5] == 'int' and attr_[0][8]:
            if attr_[0][8].find('select') != -1:
                attrOptions = db.sqlQuery('SELECT distinct value FROM firsteav_attribute_option_value\
                                         where option_id in(SELECT option_id FROM firsteav_attribute_option \
                                         where attribute_id=%s);' % attr_[0][0])
                for attrOption in attrOptions:
                    value.append(attrOption[0].decode('utf-8', 'ignore'))
        else:
            value.append(-1)
        attr = {attr_[0][2]: value}
        return attr

    def proccessRule(self, products):
        outProducts = []
        for ruleName in products:
            products_ = products[ruleName]
            if isinstance(ruleName, unicode):
                ruleName = ruleName.encode('utf-8')
            rule = self.rules[ruleName]
            for product_ in products_:
                try:
                    product_['enoughAttr'] = {}
                    product_['new_attrs'] = {}
                    for attr in rule[1].keys():
                        newAttr = rule[1][attr][0]
                        if product_['attrs'].has_key(attr):
                            value = product_['attrs'].pop(attr)
                            if self.baseAttrib[rule[0]][newAttr] == [-1]:
                                product_['new_attrs'][newAttr] = self.ruleValue(rule[1][attr], value)
                            else:
                                for value_ in self.baseAttrib[rule[0]][newAttr]:
                                    if isinstance(value, str):
                                        if value.lower().replace(' ', '') == value_.lower().replace(' ', ''):
                                            value = value_
                                            product_['new_attrs'][newAttr] = self.ruleValue(rule[1][attr], value)
                                            break
                                if not value in self.baseAttrib[rule[0]][newAttr]:
                                    product_['new_attrs'][newAttr] = ''
                                    if not product_['enoughAttr'].has_key(newAttr):
                                        product_['enoughAttr'][newAttr] = []
                                    product_['enoughAttr'][newAttr].append(value)
                        else:
                            product_['new_attrs'][newAttr] = ''
                    if len(rule) > 4:
                        value = ""
                        for attr in product_['attrs'].keys():
                            value += '%s - %s;' % (attr, product_['attrs'][attr])
                        product_['new_attrs'][rule[4]] = value
                    product_['attr_set'] = rule[0]
                    try:
                        if isinstance(product_['price'], list):
                            product_['price'] = (float(product_['price'][rule[2][0] - 1]) + rule[2][1]) * float(self.currency)
                        if product_.has_key('imagesLink'):
                            product_['imagesLink'] = self.saveImage(product_['sku'], product_['imagesLink'])
                        product_['categoryId'] = rule[3]
                        if not 'brand_name' in product_:
                            product_['brand_name'] = self.getBrand(product_['name'])
                        if not 'descr' in product_:
                            product_['descr'] = product_['name']
                        if not 'short_descr' in product_:
                            product_['short_descr'] = product_['name']
                        product_['main_type'] = ''
                        outProducts.append(product_)
                    except ValueError:
                        pass
                except TypeError:
                    pass
        return outProducts

    def ruleValue(self, rule, value):
        if rule[1]:
            replace_ = rule[1][0]
            for key in replace_.keys():
                value = value.replace(key, replace_[key])
            addToBegin = rule[1][1]
            addToEnd = rule[1][2]
            if len(rule) == 3:
                splt = rule[2]
                resultValue = ''
                for value_ in value.split(splt):
                    resultValue += addToBegin + value_ + addToEnd + ","
                value = resultValue[:len(resultValue)]
            else:
                value = addToBegin + value + addToEnd
        return value

    def saveImage(self, productSku, listImage):
        """
        Save image from distributors distributor site

        :param productSku: string
        :param listImage: list of string
        :return: list of string
        """
        if not listImage:
            return ['no_selection']
        images = []
        for imageTag in listImage:
            try:
                dir = os.path.join(STATICFILES_DIRS[0], 'product/%s/%s/' % (productSku[0], productSku[1]))
                if not os.path.exists(dir):
                    os.makedirs(dir)
                self.browser.retrieve(self.host + imageTag,
                                      '%s%s_%s.jpg' % (dir, productSku.replace('/', ''), listImage.index(imageTag)))

                images.append('%s%s_%s.jpg' % (
                    'product/%s/%s/' % (productSku[0], productSku[1]), productSku, listImage.index(imageTag)))
            except Exception:
                pass
        return images

    def encodeRules(self):
        for key in self.rules.keys():
            pop = self.rules.pop(key)
            try:
                self.rules[key.encode('utf-8')] = pop
            except UnicodeDecodeError:
                key = key.encode('cp1251')
                self.rules[key] = pop

    def getBrand(self, name):
        """
        GET brand name by product name

        :param name: string, product name
        :return: string, brand name
        """
        for brand in self.brand_name:
            if name.lower().find(brand.lower().decode('utf-8')) != -1:
                return brand
        return 'другой'.decode('utf-8')

    def checkProduct(self, sku, status=None):
        """
        Checking if product was created

        :param status: int(1,2), status product in magento
        :param sku: string, product sku
        :return: boolean, True if that product was created
        """
        product = db.sqlQuery('SELECT * FROM firstcatalog_product_entity where sku="%s";' % sku)
        if status and product:
            product = db.sqlQuery('''SELECT value FROM firstcatalog_product_entity_int
                                    where attribute_id=(SELECT attribute_id FROM firsteav_attribute
                                    where attribute_code='status') and entity_id=%s and value=%s;''' % (
                product[0][0], status))
            if product:
                return False
            else:
                return True
        if product:
            return True
        else:
            return False

    def getProductPriceBySKu(self, sku):
        product = db.sqlQuery('SELECT * FROM firstcatalog_product_entity where sku="%s";' % sku)
        price = db.sqlQuery('''SELECT value FROM firstcatalog_product_entity_decimal
                                    where attribute_id=(SELECT attribute_id FROM firsteav_attribute
                                    where attribute_code='price') and entity_id=%s''' % product[0][0])
        return price[0][0]